CCCPaste

Get products list by Id or Ref from prestasho...

link;
$id_lang  = (int)Configuration::get('PS_LANG_DEFAULT');
$currency = $context->currency ?: new Currency((int)Configuration::get('PS_CURRENCY_DEFAULT'));

// ------------------- Помощни функции -------------------
function sanitize_filename($str) {
    $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
    $str = preg_replace('/[\r\n]+/', ' ', $str);
    $str = preg_replace('/[^\pL\pN\s._-]+/u', '', $str);
    $str = trim(preg_replace('/[\s]+/u', ' ', $str));
    $str = str_replace(' ', '_', $str);
    return $str === '' ? 'product' : $str;
}

function price_fmt($amount, $currency) {
    if (class_exists('PrestaShop\\PrestaShop\\Adapter\\Product\\PriceFormatter')) {
        $pf = new PrestaShop\PrestaShop\Adapter\Product\PriceFormatter();
        return $pf->format($amount, (int)$currency->id);
    }
    return Tools::displayPrice($amount, $currency);
}

function find_product_id_by_reference($ref) {
    $ref = trim($ref);
    if ($ref === '') return null;
    $sql = 'SELECT id_product FROM '._DB_PREFIX_.'product WHERE reference = \'' . pSQL($ref) . '\'';
    $row = Db::getInstance()->getRow($sql);
    if ($row && !empty($row['id_product'])) return (int)$row['id_product'];
    // опит и в комбинациите
    $sql2 = 'SELECT pa.id_product FROM '._DB_PREFIX_.'product_attribute pa WHERE pa.reference = \'' . pSQL($ref) . '\'';
    $row2 = Db::getInstance()->getRow($sql2);
    if ($row2 && !empty($row2['id_product'])) return (int)$row2['id_product'];
    return null;
}

function get_cover_image_id($id_product) {
    $cover = Image::getCover((int)$id_product);
    return ($cover && !empty($cover['id_image'])) ? (int)$cover['id_image'] : null;
}

function image_url($link, $product, $id_image) {
    $rewrite = isset($product->link_rewrite) && is_array($product->link_rewrite)
        ? (string)reset($product->link_rewrite)
        : (isset($product->link_rewrite) ? (string)$product->link_rewrite : '');

    // Предпочитан тип изображение
    $type = null; $available = array();
    if (class_exists('ImageType') && method_exists('ImageType','getImagesTypes')) {
        $types = ImageType::getImagesTypes('products');
        foreach ($types as $t) $available[] = $t['name'];
        foreach (array('large_default','large','scene_default','home_default') as $p) {
            if (in_array($p, $available)) { $type = $p; break; }
        }
    }
    return $link->getImageLink($rewrite, $id_image, $type);
}

function image_disk_path($id_image) {
    $base = _PS_IMG_DIR_.'p/'.Image::getImgFolderStatic($id_image).$id_image;
    foreach (array('.jpg','.jpeg','.webp','.png') as $ext) {
        $path = $base.$ext; if (is_file($path)) return $path;
    }
    return $base.'.jpg';
}

function make_short_product_link(Link $link, Product $product, $id_lang) {
    $full = $link->getProductLink(
        $product->id,
        is_array($product->link_rewrite) ? reset($product->link_rewrite) : $product->link_rewrite,
        null, null, (int)$id_lang, null, 0, false
    );
    $rewrite = is_array($product->link_rewrite) ? reset($product->link_rewrite) : $product->link_rewrite;
    if ($rewrite) {
        $full = preg_replace('#-'.preg_quote($rewrite, '#').'\\.html$#u', '-.html', $full);
    } else if (substr($full, -5) !== '.html') {
        $full .= '-.html';
    }
    return $full;
}

// ------------------- Download на снимка -------------------
// ВАЖНО: не изискваме pid; стига ни iid и fname. Това позволява линкът да работи.
if (Tools::getIsset('download') && Tools::getIsset('iid') && Tools::getIsset('fname')) {
    $id_image = (int)Tools::getValue('iid');
    $fname    = sanitize_filename(Tools::getValue('fname'));
    if (!preg_match('/\.(jpe?g|png|webp)$/i', $fname)) $fname .= '.jpg';

    $path = image_disk_path($id_image);
    if (!is_file($path)) {
        header('HTTP/1.1 404 Not Found');
        header('Content-Type: text/plain; charset=utf-8');
        echo "Снимката не е намерена на диска.";
        exit;
    }
    $ext  = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    $mime = ($ext==='png') ? 'image/png' : (($ext==='webp') ? 'image/webp' : 'image/jpeg');

    // Заглавни части за изтегляне
    header('Content-Type: '.$mime);
    header('Content-Disposition: attachment; filename="'.$fname.'"');
    header('Content-Length: '.filesize($path));
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');

    readfile($path);
    exit;
}

// ------------------- Входни данни -------------------
$input = isset($_POST['refs']) ? trim($_POST['refs']) : '';
$mode  = isset($_POST['mode']) && $_POST['mode']==='id' ? 'id' : 'ref'; // 'id' или 'ref'
$lines = array();
if ($input !== '') {
    foreach (preg_split('/\r?\n/', $input) as $line) {
        $line = trim($line);
        if ($line !== '') $lines[] = $line;
    }
}

// ------------------- Сглобяване на резултати -------------------
$results = array();
foreach ($lines as $token) {
    // 1) Намери продукт ID според режима
    if ($mode === 'id') {
        $pid = ctype_digit($token) ? (int)$token : null;
    } else {
        $pid = find_product_id_by_reference($token);
    }

    if (!$pid) {
        $results[] = array('token'=>$token, 'error'=>'Не е намерен продукт.');
    } else {
        // 2) Зареди продукта
        $product = new Product($pid, true, $id_lang);
        if (!Validate::isLoadedObject($product)) {
            $results[] = array('token'=>$token, 'error'=>'Продуктът не може да бъде зареден.');
        } else {
            // 3) Цени
            $price_with    = Product::getPriceStatic($product->id, true);
            $price_without = Product::getPriceStatic($product->id, true, null, 6, null, false, false);
            $reduction_amount  = max(0, $price_without - $price_with);
            $reduction_percent = ($price_without > 0) ? round(($reduction_amount / $price_without) * 100) : 0;

            // 4) Снимка/линк
            $id_image   = get_cover_image_id($product->id);
            $img_url    = $id_image ? image_url($link, $product, $id_image) : null;
            $short_link = make_short_product_link($link, $product, $id_lang);

            // 5) Име, ref, име на файл
            $date  = date('dmY');
            $pname = is_array($product->name) ? reset($product->name) : $product->name;
            $ref   = is_array($product->reference) ? reset($product->reference) : $product->reference;

            $fname_id = ($mode === 'ref' && $token ? $token : ($ref ?: $product->id));
            $fname    = sanitize_filename($fname_id.'_'.$date.'_'.$pname).'.jpg';

            $price_clip = 'Price was: '.price_fmt($price_without,$currency)
                        .' NOW IS: '.price_fmt($price_with,$currency)
                        .' - You Save: '.$reduction_percent.'%';

            $results[] = array(
                'token' => $token,
                'id'    => $product->id,
                'name'  => $pname,
                'ref'   => $ref,
                'img_url' => $img_url,
                'id_image'=> $id_image,
                'download_fname' => $fname,
                'short_link'=> $short_link,
                'price_with' => $price_with,
                'price_without' => $price_without,
                'reduction_amount' => $reduction_amount,
                'reduction_percent'=> $reduction_percent,
                'price_clip' => $price_clip,
            );
        }
    }
}

// ------------------- HTML -------------------
?>



  
  
  Продукти по ID/Референция • PrestaShop
  


  

Извличане на продукти по ID или референция

Всеки идентификатор на нов ред
Изчисти
<?php echo htmlspecialchars($r['name'], ENT_QUOTES, 'UTF-8'); ?>
Няма снимка
Вход:
Референция:
Име:
Линк:
Цена: 0): ?> -%
Изтегли Ще се запише като:
Съвет: можете да експортирате лесно името, цената и линка чрез копиране на бутона пред всеки елемент.